<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "sms".
 *
 * @property string $id
 * @property string $user_id
 * @property string $tel
 * @property string $content
 * @property string $create_time
 * @property string $update_time
 * @property integer $admin_id
 * @property integer $auto_send
 * @property integer $send_status
 * @property string $weight
 * @property string $tpl_id
 * @property string $remark
 * @property integer $type
 */
class Sms extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sms';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'tel', 'content'], 'required'],
            [['user_id', 'admin_id', 'auto_send', 'send_status', 'weight', 'type'], 'integer'],
            [['content'], 'string'],
            [['create_time', 'update_time'], 'safe'],
            [['tel'], 'string', 'max' => 11],
            [['tpl_id', 'remark', 'var_json'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'id',
            'user_id' => '用户id',
            'tel' => '用户手机号',
            'content' => '短信详情',
            'var_json' => '替换变量的json串',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
            'admin_id' => '操作员ID',
            'auto_send' => '是否自动发送',
            'send_status' => '发送状态',
            'weight' => '优先发送权重，值高的优先发送，注册和找回密码100',
            'tpl_id' => '第三方模板id',
            'remark' => '备注',
            'type' => '发送类型',
        ];
    }

    public static function itemAlias ($type, $code = NULL)
    {
        $_items = [
            'send_status' => [
                //''  =>'全部',
                '1' => "未发送",              
                '2' => "发送中",
                '3' => "已发送",
                '4' => "失败",   
              
                             
            ],
            'type' => [
                //''  =>'状态',
                '1' => "短信",              
                '2' => "微信",
                               
            ],
            'auto_send' => [
                //''  =>'状态',
                '1' => "不自动",              
                '2' => "自动",
                               
            ],
        ];

        if (isset($code))
            return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
        else
            return isset($_items[$type]) ? $_items[$type] : false;
    }

    /*
    * 保存前执行的操作
    */
    public function beforeSave($insert) {
        if (parent::beforeSave($insert)) {
            //是否是新添加
            if($this->isNewRecord) {
                $this->create_time = date("Y-m-d H:i:s", time());
                $this->update_time = date("Y-m-d H:i:s", time());
            }else{
                $this->update_time = date("Y-m-d H:i:s", time());
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * @desc 发送短信
     * @param string $tel 电话号码
     * @param string $keyword 模板关键词
     * @param array $params 要替换模板变量的参数
     * @param int $type 发送类型：1.短信 2.微信
     * @param string $var_json 替换变量的json串（如果是sendcloud可以不传该变量）
     * @return bool
     */
    public static function sendSms($tel,$keyword,$params,$type=1,$var_json=''){

        $template_obj=Template::find()->where("keyword='{$keyword}'")->one();
        if(empty($template_obj))
            return false;
        $template=$template_obj->content;
        $tpl_id = $template_obj->tpl_id;

        $content=str_replace(array_keys($params), array_values($params), $template);

        //判断用的哪一个短信通道
        $smsType = trim(Systemconfig::getValue('sms_type'));
        if( $smsType=='sc' ){
            //sendcloud的var_json格式：{"%content%":"liubidatest"}
            $new_params = [];
            array_walk(
                $params,
                function($v, $k) use (&$new_params){
                    $key = '%'.$k.'%';
                    $new_params[$key] = $v;
                }
            );
            $var_json = json_encode($new_params);
        }

        //发送短信
        $smsModel = new self;
        $smsModel->attributes = array(
            'user_id' => 0,
            'tel' => $tel,
            'content' => $content,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => '0000-00-00 00:00:00',
            'auto_send' => 2,
            'send_status' => 1,
            'admin_id'=>1,
            'tpl_id' => $tpl_id,
            'var_json' => $var_json,
            'type' => $type,
            'weight' => 100,
        );
        if($smsModel->save(false))
            return true;
        return false;
    }

}
